package com.lottery.im.module.tim.message;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.chat.adapter.ChatAdapter;
import com.lottery.im.module.chat.ui.NewFragmentActivity;
import com.lottery.im.module.tim.face.DefaultGifEmoji;
import com.lottery.im.module.tim.face.EqualHeightSpan;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.utils.EmoticonUtil;
import com.lottery.im.util.SPUtils;
import com.lottery.im.util.transformations.CropCircleTransformation;
import com.sunhapper.spedittool.util.GifTextUtil;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMFaceElem;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.message.TIMMessageDraft;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 文本消息数据
 */
public class TextMessage extends Message {

  public TextMessage(TIMMessage message) {
    this.message = message;
  }

  public TextMessage(String s) {
    message = new TIMMessage();
    TIMTextElem elem = new TIMTextElem();
    elem.setText(s);
    message.addElement(elem);
  }

  public TextMessage(TIMMessageDraft draft) {
    message = new TIMMessage();
    for (TIMElem elem : draft.getElems()) {
      message.addElement(elem);
    }
  }

  private List<ImageSpan> sortByIndex(final Editable editInput, ImageSpan[] array) {
    ArrayList<ImageSpan> sortList = new ArrayList<>();
    for (ImageSpan span : array) {
      sortList.add(span);
    }
    Collections.sort(sortList, new Comparator<ImageSpan>() {
      @Override
      public int compare(ImageSpan lhs, ImageSpan rhs) {
        return editInput.getSpanStart(lhs) - editInput.getSpanStart(rhs);
      }
    });

    return sortList;
  }

  public TextMessage(Editable s) {
    message = new TIMMessage();
    ImageSpan[] spans = s.getSpans(0, s.length(), ImageSpan.class);
    List<ImageSpan> listSpans = sortByIndex(s, spans);
    int currentIndex = 0;
    for (ImageSpan span : listSpans) {
      int startIndex = s.getSpanStart(span);
      int endIndex = s.getSpanEnd(span);
      if (currentIndex < startIndex) {
        TIMTextElem textElem = new TIMTextElem();
        textElem.setText(s.subSequence(currentIndex, startIndex).toString());
        message.addElement(textElem);
      }
      TIMFaceElem faceElem = new TIMFaceElem();

      int index;
      try {
        index = Integer.parseInt(s.subSequence(startIndex, endIndex).toString());
      } catch (Exception e) {
        index = Arrays.asList(EmoticonUtil.emoticonData)
            .indexOf(s.subSequence(startIndex, endIndex).toString());
      }
      faceElem.setIndex(index);
      if (index < EmoticonUtil.emoticonData.length) {
        faceElem.setData(EmoticonUtil.emoticonData[index].getBytes(Charset.forName("UTF-8")));
      }
      message.addElement(faceElem);
      currentIndex = endIndex;
    }
    if (currentIndex < s.length()) {
      TIMTextElem textElem = new TIMTextElem();
      textElem.setText(s.subSequence(currentIndex, s.length()).toString());
      message.addElement(textElem);
    }
  }

  /**
   * 在聊天界面显示消息
   *
   * @param viewHolder 界面样式
   * @param context 显示消息的上下文
   */
  @Override
  public void showMessage(ChatAdapter.ViewHolder viewHolder, Context context) {

    clearView(viewHolder);
    if (checkRevoke(viewHolder)) return;
    boolean hasText = false;

    List<TIMElem> elems = new ArrayList<>();
    for (int i = 0; i < message.getElementCount(); ++i) {
      elems.add(message.getElement(i));
      if (message.getElement(i).getType() == TIMElemType.Text) {
        hasText = true;
      }
    }

    SpannableStringBuilder stringBuilder = getString(elems, context);

    if (stringBuilder.toString().startsWith(CustomMessageType.CUSTOMFACE_TYPE)) {
      //  自定义表情
      RelativeLayout layout =
          (RelativeLayout) LayoutInflater.from(context)
              .inflate(R.layout.layout_message_face_custom, null);

      ImageView image = layout.findViewById(R.id.iv_face);

      String faceContent = stringBuilder.toString();
      String faceName =
          faceContent.substring(CustomMessageType.CUSTOMFACE_TYPE.length(), faceContent.length());
      String assetPic = "";
      if (faceName.startsWith("sx")) {
        if (faceName.contains(".gif")) {
          assetPic = "file:///android_asset/sx/" + faceName;
        } else {
          assetPic = "file:///android_asset/sx/" + faceName + ".gif";
        }
      } else if (faceName.startsWith("lt")) {
        if (faceName.contains(".png")) {
          assetPic = "file:///android_asset/lt/" + faceName;
        } else {
          assetPic = "file:///android_asset/lt/" + faceName + ".png";
        }
      } else if (faceName.startsWith("xxy")) {
        if (faceName.contains(".png")) {
          assetPic = "file:///android_asset/xxy/" + faceName;
        } else {
          assetPic = "file:///android_asset/xxy/" + faceName + ".png";
        }
      }
      Glide.with(context).load(assetPic)
          .apply(new RequestOptions().fitCenter())
          .into(image);
      getBubbleView(viewHolder).addView(layout);
    } else if (stringBuilder.toString().startsWith(CustomMessageType.BUSINESSCARD_TYPE)) {
      //  名片
      View view = LayoutInflater.from(context)
          .inflate(R.layout.layout_message_business_card, null);
      ImageView ivPortrait = view.findViewById(R.id.iv_portrait);
      TextView tvName = view.findViewById(R.id.tv_name);
      TextView tvId = view.findViewById(R.id.tv_id);

      String id =
          stringBuilder.toString()
              .substring(CustomMessageType.BUSINESSCARD_TYPE.length(),
                  stringBuilder.toString().length());
      tvId.setText("ID：" + id);

      if (FriendshipInfo.getInstance().isFriend(id)) {
        FriendProfile friendProfile = FriendshipInfo.getInstance().getProfile(id);
        Glide.with(context)
            .load(friendProfile.getAvatarUrl())
            .apply(new RequestOptions()
                .bitmapTransform(new CropCircleTransformation())
                .placeholder(R.drawable.icon_conversation_de)
                .error(R.drawable.icon_conversation_de))
            .into(ivPortrait);
        tvName.setText(friendProfile.getNickName());
      } else {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        TIMFriendshipManager.getInstance().getUsersProfile(ids,
            new TIMValueCallBack<List<TIMUserProfile>>() {
              @Override public void onError(int i, String s) {
              }

              @Override public void onSuccess(List<TIMUserProfile> timUserProfiles) {
                if (null != timUserProfiles && timUserProfiles.size() > 0) {
                  TIMUserProfile userProfile = timUserProfiles.get(0);
                  Glide.with(context)
                      .load(userProfile.getFaceUrl())
                      .apply(new RequestOptions()
                          .bitmapTransform(new CropCircleTransformation())
                          .placeholder(R.drawable.icon_conversation_de)
                          .error(R.drawable.icon_conversation_de))
                      .into(ivPortrait);
                  tvName.setText(userProfile.getNickName());
                }
              }
            });
      }
      getBubbleView(viewHolder).addView(view);
      getBubbleView(viewHolder).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          onBusinesscardClick(context, id);
        }
      });
    } else if (stringBuilder.toString().startsWith(CustomMessageType.HONGBAO_TYPE)) {

      String content = stringBuilder.toString();

      //  红包
      View view = LayoutInflater.from(context)
          .inflate(R.layout.layout_hongbao, null);

      TextView tvStatus = view.findViewById(R.id.tv_status);
      TextView tvNote = view.findViewById(R.id.tv_note);
      ImageView icon = view.findViewById(R.id.icon);
      View lingquBg = view.findViewById(R.id.lingqu_bg);

      String hongbaoId;
      String note ;

      if (content.contains(Constants.HONGBAO_INFO)) {
        hongbaoId = content
            .substring(CustomMessageType.HONGBAO_TYPE.length(),
                content.indexOf(Constants.HONGBAO_INFO));
        String ly = content.substring(content.indexOf(Constants.HONGBAO_INFO) + Constants.HONGBAO_INFO.length(),
            content.length());
        if (!TextUtils.isEmpty(ly)) {
          note = ly;
        }else {
          note = "";
        }
      } else {
        note="";
        hongbaoId = content
            .substring(CustomMessageType.HONGBAO_TYPE.length(),
                content.length());
      }

      String ids =
          (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.REDPACKETS_ID_KEY, "");

      if (Arrays.asList(ids.split(","))
          .contains(hongbaoId + "_" + MyApplication.getInstance().getUserInfo().getUserId())) {
        tvStatus.setText("红包已领取");
        lingquBg.setVisibility(View.VISIBLE);
        icon.setImageResource(R.drawable.hb_2);
      } else {
        tvStatus.setText("领取红包");
        lingquBg.setVisibility(View.GONE);
        icon.setImageResource(R.drawable.hb_1);
      }

      if (TextUtils.isEmpty(note)){
        tvNote.setText("恭喜发财，大吉大利");
      }else {
        tvNote.setText(note);
      }


      getBubbleView(viewHolder).addView(view);
      getBubbleView(viewHolder).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          onHongBaoClick(hongbaoId,note);
        }
      });
    } else if (stringBuilder.toString().equals(Constants.SILENCE_TRUE) || stringBuilder.toString()
        .equals(Constants.SILENCE_FALSE)) {
      //  禁言提示
      viewHolder.leftPanel.setVisibility(View.GONE);
      viewHolder.rightPanel.setVisibility(View.GONE);
      viewHolder.systemMessage.setVisibility(View.VISIBLE);
      viewHolder.systemMessage.setText(stringBuilder.toString()
          .substring(Constants.SILENCE_START.length(), stringBuilder.toString().length()));
    } else {

      TextView tv;
      if (message.isSelf()) {
        tv = (TextView) LayoutInflater.from(context)
            .inflate(R.layout.layout_message_text_self, null);
      } else {
        tv = (TextView) LayoutInflater.from(context)
            .inflate(R.layout.layout_message_text_left, null);
      }
      if (!hasText) {
        stringBuilder.insert(0, " ");
      }

      if (!message.isSelf() && message.getConversation().getType() == TIMConversationType.Group &&
          !TextUtils.isEmpty(selfGroupCardName) && stringBuilder.toString()
          .contains("@" + selfGroupCardName)) {

        String content = stringBuilder.toString();
        String cardName = "@" + selfGroupCardName;

        int startIndex = content.indexOf(cardName);

        SpannableString spannableString = new SpannableString(stringBuilder);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF0000")), startIndex,
            startIndex + cardName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
      } else {
        GifTextUtil.setTextWithReuseDrawable(tv, new SpannableString(stringBuilder), false);
      }
      getBubbleView(viewHolder).addView(tv);
    }

    showStatus(viewHolder);
  }

  /**
   * 获取消息摘要
   */
  @Override
  public String getSummary() {
    String str = getRevokeSummary();
    if (str != null) return str;
    StringBuilder result = new StringBuilder();

    TIMGroupMemberInfo senderGroupMemberProfile = message.getSenderGroupMemberProfile();
    if (null != senderGroupMemberProfile) {
      // 说明这是群聊消息
      if (TextUtils.isEmpty(message.getSenderGroupMemberProfile().getNameCard())) {
        // 有自己的群名片
        result.append(message.getSenderProfile().getNickName() + "：");
      } else {
        // 无自己的群名片
        result.append(message.getSenderGroupMemberProfile().getNameCard() + "：");
      }
    }

    for (int i = 0; i < message.getElementCount(); ++i) {
      switch (message.getElement(i).getType()) {
        case Face:
          TIMFaceElem faceElem = (TIMFaceElem) message.getElement(i);
          byte[] data = faceElem.getData();
          if (data != null) {
            result.append(new String(data, Charset.forName("UTF-8")));
          }
          break;
        case Text:
          TIMTextElem textElem = (TIMTextElem) message.getElement(i);
          String elemText = textElem.getText();
          if (elemText.startsWith(CustomMessageType.CUSTOMFACE_TYPE)) {
            result.append("[表情信息]");
          } else if (elemText.startsWith(CustomMessageType.BUSINESSCARD_TYPE)) {
            result.append("[名片信息]");
          } else if (elemText.startsWith(CustomMessageType.HONGBAO_TYPE)) {
            result.append("[红包信息]");
          } else if (elemText.equals(Constants.SILENCE_TRUE) || elemText.equals(
              Constants.SILENCE_FALSE)) {
            result.append(elemText.substring(Constants.SILENCE_START.length(), elemText.length()));
          } else {
            result.append(elemText);
          }
          break;
      }
    }

    if (result.toString().equals(GroupTipMessage.NO_TIP_TEXT))
      return "";

    return result.toString();
  }

  /**
   * 保存消息或消息文件
   */
  @Override
  public void save() {

  }

  private static int getNumLength(int n) {
    return String.valueOf(n).length();
  }

  public static SpannableStringBuilder getString(List<TIMElem> elems, Context context) {
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
    for (int i = 0; i < elems.size(); ++i) {
      switch (elems.get(i).getType()) {
        case Face:
          TIMFaceElem faceElem = (TIMFaceElem) elems.get(i);
          //int startIndex = stringBuilder.length();
          //try {
          AssetManager am = context.getAssets();

          DefaultGifEmoji defaultGifEmoji;
          if (faceElem.getIndex() < EmoticonUtil.emoticonData.length) {
            defaultGifEmoji =
                new DefaultGifEmoji(am, String.format("emoticon/%d.gif", faceElem.getIndex()),
                    EmoticonUtil.emoticonData[faceElem.getIndex()]);
          } else {
            defaultGifEmoji =
                new DefaultGifEmoji(am, String.format("emoticon/%d.gif", faceElem.getIndex()),
                    String.format("emoticon/%d.gif", faceElem.getIndex()));
          }

          Drawable gifDrawable = defaultGifEmoji.getDrawable(context);
          ImageSpan imageSpan = new EqualHeightSpan(gifDrawable);
          stringBuilder.append(defaultGifEmoji.getEmojiText(), imageSpan,
              Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

          //
          //InputStream is = am.open(String.format("emoticon/%d.gif", faceElem.getIndex()));
          //if (is == null) continue;
          //Bitmap bitmap = BitmapFactory.decodeStream(is);
          //Matrix matrix = new Matrix();
          //int width = bitmap.getWidth();
          //int height = bitmap.getHeight();
          //matrix.postScale(2, 2);
          //Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
          //    width, height, matrix, true);
          //ImageSpan span = new ImageSpan(context, resizedBitmap, ImageSpan.ALIGN_BASELINE);
          //stringBuilder.append(String.valueOf(faceElem.getIndex()));
          //stringBuilder.setSpan(span, startIndex, startIndex + getNumLength(faceElem.getIndex()),
          //    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          //is.close();
          //} catch (IOException e) {
          //
          //}
          break;
        case Text:
          TIMTextElem textElem = (TIMTextElem) elems.get(i);
          stringBuilder.append(textElem.getText());
          break;
      }
    }
    return stringBuilder;
  }

  private void onBusinesscardClick(Context context, String id) {
    if (id.equals(MyApplication.getInstance().getThirdAccId())) {
      // 自己
      NewFragmentActivity.createSelfProfile(context);
    } else {
      // 别人
      NewFragmentActivity.create(context, NewFragmentActivity.FragmentInfoType.Other, id);
    }
  }

  private void onHongBaoClick(String id,String note) {
    if (null != mOnHongBaoClickListener) {
      mOnHongBaoClickListener.OnHongBaoClick(id,note);
    }
  }
}